// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  traceUser: true,
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const { requestId, action } = event // action: confirm/reject
  const { OPENID: currentOpenid } = cloud.getWXContext()

  try {
    // 1. 获取请求详情
    const request = await db.collection('exchange_requests')
      .doc(requestId)
      .get()

    if (!request.data || request.data.target_openid !== currentOpenid) {
      return {
        code: 1,
        msg: '无权操作此请求'
      }
    }

    // 2. 更新请求状态
    await db.collection('exchange_requests')
      .doc(requestId)
      .update({
        data: {
          status: action === 'confirm' ? 'confirmed' : 'rejected',
          handle_time: db.serverDate()
        }
      })

    if (action === 'confirm') {
      // 3. 确认交换：保存双方交换记录
      const { sender_openid, target_openid, sender_info } = request.data
      
      // 获取目标用户的名片信息
      const targetCard = await db.collection('business_cards')
        .where({ _openid: target_openid })
        .limit(1)
        .get()

      // 保存到发送方的交换记录
      await db.collection('user_exchanges').add({
        data: {
          user_openid: sender_openid,
          target_card_id: targetCard.data[0]._id,
          target_info: targetCard.data[0],
          create_time: db.serverDate()
        }
      })

      // 保存到接收方的交换记录
      await db.collection('user_exchanges').add({
        data: {
          user_openid: target_openid,
          target_card_id: sender_info.cardId,
          target_info: sender_info,
          create_time: db.serverDate()
        }
      })

      // 4. 发送确认消息给请求方
      await cloud.openapi.templateMessage.send({
        touser: sender_openid,
        page: `/pages/card/CardDetail?id=${sender_info.cardId}`,
        data: {
          keyword1: {
            value: '名片交换成功'
          },
          keyword2: {
            value: '对方已同意您的名片交换请求'
          }
        },
        templateId: '你的模板消息ID'
      })
    }

    return {
      code: 0,
      msg: action === 'confirm' ? '已同意交换' : '已拒绝交换'
    }
  } catch (err) {
    console.error('处理响应失败', err)
    return {
      code: 1,
      msg: '处理失败',
      error: err.message
    }
  }
}